﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DreamHome.Services;
using DreamHome.Models;
using System.Globalization;
using System.IO;

namespace DreamHome.Repositories
{
    class StaffRepository
    {
        private readonly String _filePath;
        private readonly String _dateFormat;
        private readonly String _fileDelimeter;

        public StaffRepository(string filePath, string dateFormat, string fileDelimeter)
        {
            if (String.IsNullOrWhiteSpace(filePath))
                throw new ArgumentNullException("filePath");

            if (String.IsNullOrWhiteSpace(dateFormat))
                throw new ArgumentNullException("dateFormat");

            if (String.IsNullOrWhiteSpace(fileDelimeter))
                throw new ArgumentNullException("fileDelimeter");

            _filePath = filePath;
            _dateFormat = dateFormat;
            try
            {
                int number = Convert.ToInt32(fileDelimeter);
            }
            catch (FormatException e)
            {
                _fileDelimeter = fileDelimeter;
                return;
            }
                char ch = System.Convert.ToChar(System.Convert.ToUInt32(fileDelimeter));
                _fileDelimeter = new String(ch, 1);
        }
        public void CreateStaff(Staff staff)
        {
            String PrepaiedRecord = staff.StaffNo + _fileDelimeter + staff.FName + _fileDelimeter + staff.LName + _fileDelimeter +
            staff.Position + _fileDelimeter + staff.Sex + _fileDelimeter + staff.DateOfBirth.ToString("d", CultureInfo.CreateSpecificCulture("en-US")) +
            _fileDelimeter + staff.Salary + _fileDelimeter + staff.BranchNo + _fileDelimeter + staff.IsValid + _fileDelimeter;
            File.AppendAllText(_filePath, PrepaiedRecord + "\r\n");
        }

        #region SELECT ALL LINES FROM STAFF file
        public List<Staff> SelectAllFromStaff(List<Staff> allFromStaff)
        {
            char[] seps = { ';' };
            char[] sepDOB = { '/' }; // using for birthday only

            foreach (string record in File.ReadAllLines(_filePath))
            {
                Staff tmpStaffRecord = new Staff();
               string[] parts = record.Split(seps);        // deviding of string on parts
                tmpStaffRecord.StaffNo = parts[0];
                tmpStaffRecord.FName = parts[1];
                tmpStaffRecord.LName = parts[2];
                tmpStaffRecord.Position = parts[3];
                tmpStaffRecord.Sex = parts[4];
                string[] partDOB = parts[5].Split(sepDOB);        // deviding of string on parts
                int month = Convert.ToInt32(partDOB[0]);
                int day = Convert.ToInt32(partDOB[1]);
                int year = Convert.ToInt32(partDOB[2]);
                tmpStaffRecord.DateOfBirth = new DateTime(year, month, day);
                tmpStaffRecord.Salary = parts[6];
                tmpStaffRecord.BranchNo = parts[7];
                tmpStaffRecord.IsValid = parts[8];

                allFromStaff.Add(tmpStaffRecord);
            }
            return allFromStaff;
        }
        public List<Staff> SelectAllYesValidFromStaff(List<Staff> allFromStaff)  // use for case when IsValid == "Yes"
        {
            List<Staff> allStaffRecord = new List<Staff>();
            List<Staff> yesStaffRecord = new List<Staff>();

            allStaffRecord = SelectAllFromStaff(allStaffRecord);
            foreach (Staff record in allStaffRecord)
            {
                if (record.IsValid == "Yes") 
                    yesStaffRecord.Add(record);
            }
            return yesStaffRecord;
        }
        #endregion


        #region delete staffNo 
        public void deleteStaffNo(String staffNoWichWasDeleted)
        {
            List<Staff> allFromStaffTable = new List<Staff>();
            allFromStaffTable = SelectAllFromStaff(allFromStaffTable);
            int i = 0;
            int lenghOfRecord;
            string str;
            int[] lenthOfRecord = new int[allFromStaffTable.Count];
            int summaryCount = 0;
            foreach(Staff record in allFromStaffTable)
            {
                string DateOfBirthOriginalInFile = record.DateOfBirth.ToString("d", CultureInfo.CreateSpecificCulture("en-US"));
                str = record.StaffNo + ";" + record.FName + ";" + record.LName + ";" + record.Position +
                ";" + record.Sex + ";" + DateOfBirthOriginalInFile + ";" + record.Salary + ";" +
                record.BranchNo + ";" + record.IsValid + ";";
                lenthOfRecord[i] = str.Length;
                if (record.StaffNo == staffNoWichWasDeleted && record.IsValid != "No!")
                {
                    summaryCount += lenthOfRecord[i];
                    break;
                }
                else summaryCount += lenthOfRecord[i] + 2;
                i++;
            }

            FileStream f = null;
            char ch;

            try
            {
                f = new FileStream(_filePath, FileMode.Open);
                int number = summaryCount - 4;
                f.Seek(number, SeekOrigin.Begin);
                string msg = "No!";
                byte[] msgAsByteArray = Encoding.Default.GetBytes(msg);

                f.Write(msgAsByteArray, 0, 3);
            }
            catch (IOException exc)
            {
                Console.WriteLine("Error of input-output");
            }
            finally
            {
                f.Close();
            }

        }
        #endregion
    }
}
